;
(function($) {
    function pagination(element, options) {
        //合并配置
        this.options = $.extend({}, pagination.options, options);
        //指定分页容器插入到的目标元素
        this.appendToEle = element;
        //添加样式名称
        this.appendToEle.addClass(this.options.style);
        //页码最大显示长度
        this.pageLength = this.options.pageLength;
        //根据配置返回ajax参数
        this.origParam = pagination.returnAjaxParam(this.options);
        this.ajaxParam = pagination.returnAjaxParam(this.options);
        //选择分页模版
        this.template = this.options.template in pagination.template ? pagination.template[this.options.template].call(this) : pagination.template['default'].call(this);
        //初始跳转到指定页面
        this.options.run && this.target(this.options.currentPage);
    }
    /**
     * 跳转到指定页
     * @method isElement
     * @param element 待检测的元素
     * @return boolean
     */
    pagination.prototype.target = function(number, callback) {
        var _self = this;
        var _number = parseInt(number);
        if (isNaN(number) || _number < 1) {
            _number = 1;
        } else {
            if ($.type(_self.pageCount) == 'number') {
                if (_number > _self.pageCount) {
                    _number = _self.pageCount;
                }
            } else {
                _number = 1;
            }
        }
        _self.currentPage = _number;
        var _success = this.origParam.success;
        this.ajaxParam.data.page = _self.currentPage;
        this.ajaxParam.success = function(data) {
            _self.pageCount = data[_self.options.pageCount];
            _self.appendToEle.html(_self.template(_self.currentPage, _self.pageCount, _self.pageLength));
            $.isFunction(_success) && _success(data);
            $.isFunction(_self.options.ajaxSuccess) && _self.options.ajaxSuccess.call(_self, data);
            $.isFunction(callback) && callback.call(_self, data);
        }
        $.ajax(this.ajaxParam);
        return _self;
    }
    /**
     * 切换到上一页
     * @method new pagination().prev()
     * @return pagination
     */
    pagination.prototype.prev = function() {
        return this.target(this.currentPage - 1);
    }
    /**
     * 切换到下一页
     * @method new pagination().next()
     * @param key {String} 参数键名
     * @return 参数值
     */
    pagination.prototype.next = function() {
        return this.target(this.currentPage + 1);
    }
    /**
     * 切换到首页
     * @method new pagination().first()
     * @return pagination
     */
    pagination.prototype.first = function() {
        return this.target(1);
    }
    /**
     * 切换到尾页
     * @method new pagination().last()
     * @return pagination
     */
    pagination.prototype.last = function() {
        return this.target(this.pageCount);
    }
    /**
     * 以当前参数请求服务器
     * @method new pagination().refresh()
     * @return pagination
     */
    pagination.prototype.refresh = function() {
        return this.target(this.currentPage);
    }
    /**
     * 以原始参数请求服务器
     * @method new pagination().reload()
     * @return pagination
     */
    pagination.prototype.reload = function() {
        this.ajaxParam = $.extend({}, this.origParam);
        return this.target(this.ajaxParam.data.page);
    }
    /**
     * 以原始参数上扩展新参数并请求服务器
     * @method new pagination().assign()
     * @return pagination
     */
    pagination.prototype.assign = function(param, callback) {
        this.ajaxParam.data = $.extend({}, this.origParam.data, param);
        return this.target(this.ajaxParam.data.page, callback);
    }
    /**
     * 设置请求参数
     * @method new pagination().setParam()
     * @return pagination
     */
    pagination.prototype.setParam = function(param) {
        $.extend(true, this.ajaxParam.data, param)
    }
    pagination.options = {
        style: 'think-pagination',
        template: 'default',
        run: true,
        url: null,
        type: 'POST',
        dataType: 'json',
        currentPage: 1, //指定当前页面
        pageCount: 'pageCount', //服务器端总页数对应字段名
        pageLength: 5, //设置页码最大显示长度
        data: {
            pageSize: 12
        },
        ajaxStart: null,
        ajaxSuccess: null,
        onChange: null, //页面发生改变时触发回调函数
        onItemClick: null //点击分页元素是触发回调函数
    }
    /**
     * 返回ajax参数集
     * @method pagination.returnAjaxParam(param)
     * @param param 参数
     * @return Object
     */
    pagination.returnAjaxParam = function(param) {
        return $.extend({
            url: param.url,
            type: param.type,
            dataType: param.dataType,
            data: param.data || {},
            beforeSend: param.ajaxStart
        }, param.ajax);
    }
    /**
     * 跳转到指定页
     * @method isElement
     * @param element 待检测的元素
     * @return boolean
     */
    pagination.template = {
        'default': function() {
            var _self = this;
            //页面省略长度
            this.ellipsisLength = Math.ceil(this.pageLength / 2);
            //绑定分页事件
            this.appendToEle.delegate('[data-page]', 'click', function() {
                _self.target($(this).data('page'));
                $.isFunction(_self.options.onItemClick) && _self.options.onItemClick.call(_self, $(this));
                return false;
            });
            return function(current, count, length) {
                var _html = '';
                if (count > 1) {
                    var _number = '';
                    var _start = current - this.ellipsisLength + 1;
                    if (_start <= 0) {
                        _start = 1;
                    }
                    var _end = _start + length - 1;
                    if (_end > count) {
                        _end = count;
                        if (_end > length) {
                            _start = count - length;
                        } else {
                            _start = 1;
                        }
                    }
                    for (var i = _start; i <= _end; i++) {
                        if (i == current) {
                            _number += '<a class="page-number page-current">' + i + '</a>';
                        } else {
                            _number += '<a class="page-number" data-page="' + i + '">' + i + '</a>';
                        }
                    }
                    var _first = '<a class="page-first" data-page="1">1</a>';
                    var _last = '<a class="page-last" data-page="' + count + '">' + count + '</a>';
                    var _prev = '<a class="page-prev" data-page="' + (current - 1) + '">上一页</a>';
                    var _next = '<a class="page-next" data-page="' + (current + 1) + '">下一页</a>';
                    var _prevEllipsis = '<span class="page-ellipsis">...</span>';
                    var _nextEllipsis = '<span class="page-ellipsis">...</span>';
                    if (current == 1) {
                        _prev = '<a class="page-prev page-disabled">上一页</a>';
                    }
                    if (current == count) {
                        _next = '<a class="page-next page-disabled">下一页</a>';
                    }
                    if (current <= this.ellipsisLength || count <= length) {
                        _first = '';
                        _prevEllipsis = '';
                    }
                    if (current > count - this.ellipsisLength || count <= length) {
                        _last = '';
                        _nextEllipsis = '';
                    }
                    _html += _prev + _first + _prevEllipsis + _number + _nextEllipsis + _last + _next;
                }
                return _html;
            }
        }
    }
    $.pagination = function(element, options) {
        return new pagination(element, options);
    }
    $.pagination.extend = function(name, object) {
        if ($.type(name) == 'string') {
            if ($.isPlainObject(object)) {
                if ('init' in object && 'temp' in object) {
                    $.extend(pagination.template[name], object);
                } else {
                    console.error('必须实现init和temp方法');
                }
            }
        }
    }
    $.fn.pagination = function(options) {
        return new pagination($(this), options);
    }
})(jQuery);
